package getOscillogram;

/**
 * @projectName: code-snippet
 * @className: CRC8
 * @description: 实现自定义CRC运算（照抄chat_gpt)
 * @author: JLONG
 * @date: 2024/9/4 11:08
 * @version: 1.0
 */
public class CRC8 {

    private static final int POLYNOMIAL = 0x07; // CRC polynomial

    public static String getValue(String inputData) {
        return getValue(inputData, "Hex", 0xFF);
    }

    public static String getValue(String inputData, String format, int initValue) {
        byte[] data = null;
        int crc = initValue;
        switch (format) {
            case "Hex":
                data = hexStringToByteArray(inputData);
                break;
            case "String":
                break;
            case "Base64":
                break;
        }
        for (byte b : data) {
            crc ^= b; // 将数据字节与CRC寄存器异或
            for (int i = 0; i < 8; i++) {
                if ((crc & 0x80) != 0) { // 检查最高位是否为1
                    crc = (crc << 1) ^ POLYNOMIAL; // 左移并与多项式异或
                } else {
                    crc <<= 1; // 仅左移
                }
            }
        }

        return Integer.toHexString(crc &= initValue).toUpperCase();
    }

    // 将16进制字符串转换为字节数组
    private static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    public static void main(String[] args) {
        System.out.println(CRC8.getValue("BF83"));
    }
}
